<template>
  <px-scrollbar class="view-equip-detail">
    <div class="view-task-detail">
      <div class="view-task-title">
        <px-button type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
        <div class="text">{{ detailData.workOrderName }}</div>
        <px-tag
          effect="plain"
          :style="{
            color: `${tagColorList[detailData.workOrderStatus]}`,
            border: `1px solid ${tagBorderColorList[detailData.workOrderStatus]}`,
            backgroundColor: `${tagBgColorList[detailData.workOrderStatus]}`
          }"
        >
          {{ detailData.workOrderStatusDesc }}
        </px-tag>
      </div>
      <div>
        <px-button v-if="drawerType === 'execute'" type="primary" :disabled="lengthOfRecord < 1 || !isCanEdit" @click="handleFinish">
          完成维修
        </px-button>
        <px-button v-if="detailData.approverId === userInfo.userId && detailData.workOrderStatus === 2" type="primary" @click="isAuditShow = true">
          审核
        </px-button>
        <px-button
          v-if="detailData.approverId === userInfo.userId && detailData.workOrderStatus === 2"
          type="primary"
          plain
          @click="isForwardShow = true"
        >
          转审
        </px-button>
      </div>
    </div>
    <div class="view-task">
      <div class="view-task-item">
        <div class="label">工单创建人：</div>
        <div class="text">{{ detailData.createName }}</div>
      </div>
      <div class="view-task-item">
        <div class="label">审核人：</div>
        <div class="text">{{ detailData.approverName }}</div>
      </div>
      <div class="view-task-item">
        <div class="label">执行人：</div>
        <div class="text">{{ detailData.executorInfoList }}</div>
      </div>
      <div class="view-task-item">
        <div class="label">故障类型：</div>
        <div class="text">{{ detailData.faultTypeDesc }}</div>
      </div>
      <div class="view-task-item">
        <div class="label">报修时间：</div>
        <div class="text">{{ detailData.createTime }}</div>
      </div>
      <div class="view-task-item">
        <div class="label">审核时间：</div>
        <div class="text">{{ detailData.completionTime }}</div>
      </div>
      <div class="view-task-item">
        <div class="label">执行时间：</div>
        <div class="text">{{ detailData.acceptTime }}</div>
      </div>
    </div>
    <!-- <div class="view-task" /> -->
    <CustomTabs :tabList="tabList" :activeName="activeName" :before-leave="handleBeforeLeave" />
    <MaintainInfo v-if="activeName === 'first'" :detailData="detailData" :moduleName="moduleName" />
    <MaintainRecord
      v-if="activeName === 'second'"
      v-model:isCanEdit="isCanEdit"
      v-model:lengthOfRecord="lengthOfRecord"
      :userInfo="userInfo"
      :moduleName="moduleName"
      :activeName="activeName"
      :detailData="detailData"
      :drawerType="drawerType"
    />
    <!-- <DealProcess v-if="activeName === 2" :detailData="detailData" /> -->
    <AuditDialog :visible="isAuditShow" :taskId="detailData.id" @closeDialog="isAuditShow = false" @queryTable="backMainPage" />
    <!-- 转审弹窗 -->
    <ForwardDialog
      :visible="isForwardShow"
      :taskId="detailData.id"
      :userInfo="userInfo"
      @closeDialog="isForwardShow = false"
      @queryTable="backMainPage"
    />
    <!--完成确认弹窗-->
    <px-dialog v-model="isFinishShow" title="完成确认" width="900px" destroy-on-close append-to-body @close="handleCancelFinish">
      <px-form ref="finishRef" :model="formValue" :rules="rules" label-width="120px">
        <px-row>
          <px-col :span="24">
            <px-form-item label="故障类型" prop="faultType">
              <px-cascader
                ref="cascaderRef"
                v-model="formValue.faultType"
                style="width: 100%"
                :props="{ value: 'faultTypeCode', label: 'faultTypeDesc', children: 'faultTypes' }"
                :options="faultTypeList"
                placeholder="请选择故障类型"
                clearable
                filterable
              />
            </px-form-item>
          </px-col>
          <px-col :span="24">
            <px-form-item label="备注" prop="remark">
              <px-input
                v-model="formValue.remark"
                type="textarea"
                placeholder="请输入备注"
                :autosize="{ minRows: 2, maxRows: 4 }"
                maxlength="1000"
                clearable
              />
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
      <template #footer>
        <div class="dialog-footer">
          <px-button @click="handleCancelFinish">取 消</px-button>
          <px-button type="primary" @click="handleSubmitFinish(finishRef)">确 定</px-button>
        </div>
      </template>
    </px-dialog>
  </px-scrollbar>
</template>

<script setup lang="ts">
import { getMaintainFaultType } from "@/api/erc/learn";
import { detailMaintainList, finishMaintain, getMaintainOrderNum, getModuleName } from "@/api/erc/maintain";
import CustomTabs from "@/components/Tabs/index.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, onMounted, reactive, ref, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import AuditDialog from "./AuditDialog.vue";
import MaintainInfo from "./MaintainInfo.vue";
import MaintainRecord from "./MaintainRecord.vue";
import ForwardDialog from "./TransferDialog.vue";

const route = useRoute();
const router = useRouter();

defineOptions({
  name: "ERC_MAINTAIN_DETAIL"
});

// 表单校验规则
const rules = computed(() => ({
  faultType: [{ required: true, message: "请选择故障类型", trigger: ["blur", "change"] }]
}));

const finishRef = ref();
const cascaderRef = ref();

const state = reactive<Record<string, any>>({
  activeName: "first",
  detailData: {},
  isAuditShow: false,
  isForwardShow: false,
  userInfo: {},
  moduleName: "",
  drawerType: "",
  isCanEdit: true,
  lengthOfRecord: 0,
  formValue: {},
  isFinishShow: false,
  faultTypeList: []
});

const {
  activeName,
  detailData,
  isAuditShow,
  isForwardShow,
  drawerType,
  userInfo,
  moduleName,
  isCanEdit,
  lengthOfRecord,
  formValue,
  isFinishShow,
  faultTypeList
} = toRefs(state);

const tabList = ref([
  { name: "first", label: "维修结果" },
  { name: "second", label: "维修记录" }
]);

const tagColorList = {
  0: "#F59E0B", // 待维修
  1: "#3B82F6", // 维修中
  2: "#F59E0B", // 审核中
  3: "#EF4444", // 已驳回
  4: "#10B981", // 已完成
  5: "#909399", // 已撤销
  6: "#9254DE" // 驳回不通过
};

const tagBorderColorList = {
  0: "#FCE2B6", // 待维修
  1: "#C6E2FF", // 维修中
  2: "#FCE2B6", // 审核中
  3: "#FAC7C7", // 已驳回
  4: "#B7EAD9", // 已完成
  5: "#E9E9EB", // 已撤销
  6: "#DDC2FF" // 驳回不通过
};

const tagBgColorList = {
  0: "#FEF5E6", // 待维修
  1: "#ECF5FF", // 维修中
  2: "#FEF5E6", // 审核中
  3: "#FEECEC", // 已驳回
  4: "#E8F8F3", // 已完成
  5: "#F4F4F5", // 已撤销
  6: "#F2E7FF" // 驳回不通过
};

const queryType = async () => {
  const res = await getMaintainFaultType({});
  faultTypeList.value = res || [];
};

const handleCancelFinish = () => {
  finishRef.value.resetFields();
  isFinishShow.value = false;
};

const handleBeforeLeave = (cur, old) => {
  if (!isCanEdit.value) {
    PxMessage.warning("当前有维修记录未保存，请处理后再操作");
    return false;
  }
  activeName.value = cur;
};

/** 提交按钮 */
const handleSubmitFinish = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const { faultType, remark } = formValue.value;
      await finishMaintain({ id: route.query.id, remark, faultType: faultType[1] });
      PxMessage.success("完成维修成功");
      handleCancelFinish();
      backMainPage();
    }
  });
};

// 获取getModuleName
const getModuleNameValue = async () => {
  const data = await getModuleName();
  moduleName.value = data;
};

onMounted(async () => {
  userInfo.value = JSON.parse(localStorage.getItem("userInfo"));
  getModuleNameValue();
  const { id, type, alarmId } = route.query;
  let orderId = "";
  if (alarmId) {
    orderId = await getMaintainOrderNum({ maintenanceSource: "ALARM", relatedOrderNum: alarmId });
  }
  drawerType.value = type;
  const res = await detailMaintainList({ id: id || orderId });
  const { executorInfoList, faultImageList } = res;
  const arr = [];
  executorInfoList?.forEach(item => {
    arr.push(item.executorName);
  });
  detailData.value = { ...res, executorInfoList: arr.join("，"), faultImageList: faultImageList || [] } || {};
  if (type === "execute") {
    activeName.value = "second";
    // handleBeforeLeave("second", "");
    // handelTabSelected("second");
  }
});

// const handelTabSelected = selectName => {
//   activeName.value = selectName;
// };

const backMainPage = () => {
  if (!isCanEdit.value) {
    PxMessage.warning("当前有维修记录未保存，请处理后再操作");
    return;
  }
  activeName.value = "first";
  router.push("/erc/maintain");
};
const handleFinish = () => {
  console.log("长度", lengthOfRecord);
  if (!isCanEdit.value) {
    PxMessage.warning("当前有维修记录未保存，请处理后再操作");
    return;
  }
  if (lengthOfRecord.value === 0) {
    PxMessage.warning("请至少添加并保存一条操作记录");
    return;
  }
  PxMessageBox.confirm(`请确认已经保存当前进度，否则内容可能会丢失`, "提示", {
    confirmButtonText: "完成维修",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      isFinishShow.value = true;
      queryType();
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/view-detail.scss");

.view-equip-detail {
  padding: 20px;
}

.view-task-detail {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;

  .view-task-title {
    // width: 25%;
    display: flex;
    flex-direction: row;
    align-items: center;

    .text {
      margin-right: 8px;
      margin-left: 16px;
      font-size: 20px;
      font-weight: 600;
      line-height: 1;
      color: rgb(0 0 0 / 90%);
    }
  }
}

.view-task {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  // align-items: center;

  .view-task-item {
    display: flex;
    flex-direction: row;
    width: 25%;
    margin: 10px 0;
    font-size: 14px;

    .label {
      width: 84px;
      color: rgb(0 0 0 / 80%);
    }

    .text {
      // flex: 1;
      font-weight: 600;
      color: rgb(0 0 0 / 80%);
    }
  }
  // .view-task-item:last-child {
  //   width: 100%;
  // }
}
</style>
